<template>
  <basic-container>
    <div class="app-container calendar-list-container">
      <!-- <div class="filter-container">
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 @click="handleCreateCom"
                 type="primary"
                 icon="edit">添加社区
      </el-button>
    </div> -->
      <avue-tree-table :option="option" v-loading="listLoading">
        <el-table-column label="操作" width="490">
          <template slot-scope="scope">
            <el-button @click="handleCreate(scope.row)" size="small" v-if="scope.row.deviceType === 'company'" type="primary" plain>添加物联网设备</el-button>
            <el-button @click="handleUpdate(scope.row)" size="small" type="success" plain>编辑</el-button>
            <el-button @click="del(scope.row)" size="small" type="danger" plain>删除</el-button>
            <!-- <el-button v-if="scope.row.deviceType !== 'house'"
                     @click="handleQr(scope.row)"
                     size="small"
                     type="primary"
                     plain>添加二维码</el-button> -->
            <el-button @click="checkPower(scope.$index, scope.row)" size="small" type="primary" plain v-if="scope.row.type==='2'">电表列表</el-button>
            <el-button @click="syncIC(scope.$index, scope.row)" size="small" type="primary" v-if="scope.row.children.length===0" plain>同步</el-button>
            <!-- <el-button @click="deviceInit(scope.$index, scope.row)" size="small" type="primary" v-if="scope.row.children.length===0" plain>初始化</el-button> -->
          </template>
        </el-table-column>
      </avue-tree-table>
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="closeForm('form')">
        <el-form :model="form" ref="form" :rules="rules" label-width="100px">
          <el-form-item label="编号" prop="did" v-if="dialogStatus == 'update'">
            <el-input v-model="form.id" placeholder="编号" :disabled="true"></el-input>
            <el-input v-if="dialogStatus=='c'" v-model="form.guardPid"></el-input>
            <el-input v-if="dialogStatus=='c'" v-model="form.gcommunityId"></el-input>
          </el-form-item>
          <el-form-item label="上级设备" prop="pName">
            <el-input v-model="pName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="form.deviceName" placeholder="门禁名称"></el-input>
          </el-form-item>
          <el-form-item label="设备号" prop="deviceId">
            <el-input v-model="form.deviceId" placeholder="设备号"></el-input>
          </el-form-item>
          <!-- <el-form-item label="设备类型"
                      prop="deviceType">
          <avue-crud-select v-model="form.deviceType"
                            :dic="DIC.deviceTypeOptions"
                            clearable
                            placeholder="设备类型"></avue-crud-select>
        </el-form-item> -->
          <el-form-item label="类型" prop="type">
            <avue-crud-select v-model="form.type" :dic="DIC.typeOptions" clearable placeholder="类型"></avue-crud-select>
          </el-form-item>
          <el-form-item label="楼层" prop="floor" v-if="typeWatch">
            <avue-crud-input v-model.number="form.floor" placeholder="楼层"></avue-crud-input>
          </el-form-item>
          <el-form-item label="用户上限" prop="userMax">
            <el-input v-model.number="form.userMax" placeholder="用户上限"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('form')">取 消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
          <el-button v-else type="primary" @click="update('form')">修 改</el-button>
        </div>
      </el-dialog>

      <!--初始二维码管理界面-->
      <el-dialog title="初始二维码管理" width="50%" :visible.sync="addQrInfoFormVisible">
        <avue-crud :option="guardQrOption" ref="crud" v-model="guardQrForm" :page="guardPage" :data="guardQrData" :table-loading="guardQrLoading" :before-open="beforeQrOpen" :before-close="beforeQrClose" @refresh-change="refreshQrChange" @current-change="currentQrChange" @row-del="rowQrDel" @row-update="rowQrUpdate" @row-save="rowQrSave">
          <template slot="imgPath" slot-scope="scope">
            <el-button @click="showImgPath(scope.row)">查看</el-button>
          </template>
          <template slot-scope="scope" slot="imgPathForm">
            <el-col :span="24">
              <el-form-item prop="imgPath">
                <el-upload class="upload-demo" action="/entrance-guard/initialQrManage/upload" :on-preview="imgHandlePreview" :on-remove="imgHandleRemove" :before-upload="beforeImgUpload" :file-list="imgList" :headers="uploadHeader" :data="uploadParams" :on-success="imgSuccess" :limit="imgLimit" :on-exceed="imgExceed" :before-remove="beforeRemove" list-type="picture">
                  <el-button size="small" type="primary">上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传图片</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </template>
        </avue-crud>
      </el-dialog>

      <el-dialog title="图片" :visible.sync="imgFormVisible">
        <el-row>
          <el-col v-for="(imgPath,index) in imgListShow" :key="index">
            <el-card :body-style="{padding:'0px'}">
              <img :src="imgPath" class="image" />
            </el-card>
          </el-col>
        </el-row>
      </el-dialog>

      <!--电表信息维护界面-->
      <el-dialog title="电表列表" width="50%" :visible.sync="checkPowerFormVisible" :close-on-click-modal="false">
        <avue-crud :option="checkICOption" ref="checkPowerCrud" v-model="checkPowerForm" :page="guardPage" :data="checkPowerData" :table-loading="guardCheckPowerLoading" @refresh-change="refreshCheckPowerChange" @current-change="currentCheckPowerChange" @row-del="rowDel" @row-save="rowSave">
          <template slot-scope="scope" slot="checkPowerForm">
            <avue-crud-input v-model="checkPowerForm.id" :disabled="scope.column.disabled" :placeholder="scope.column.placeholder"></avue-crud-input>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button @click="$refs.crud.rowDel(scope.row,scope.$index )" size="small" type="danger" plain>删除</el-button>
          </template>
        </avue-crud>
      </el-dialog>

    </div>
  </basic-container>
</template>



<script>
import {
  fetchDeviceTree,
  add,
  put,
  del,
  syncByDeviceId,
  deviceInit
} from '@/api/device'
import {
  getIcInfoById,
  getPowerById,
  delPowerObj,
  addPowerObj,
  putPowerObj
} from '@/api/guard/'
import { validatenull } from '@/util/validate'
import { getToken, setToken, removeToken } from '@/util/auth'
import request from '@/router/axios'
import {
  fetchList,
  addObj,
  putObj,
  delObj,
  getImg,
  communityList,
  buildingList,
  unitList,
  getCommunityById,
  getBuildingById,
  getUnitById
} from '@/api/initialqr'
import DIC from './dic.js'
export default {
  name: 'treeTableDemo',
  data() {
    return {
      row: {},
      id: '',
      checkPowerForm: {},
      DIC: DIC,
      checkPowerData: [],
      guardCheckPowerLoading: false,
      checkPowerFormVisible: false, // 查看IC卡界面是否显示
      rules: {
        deviceId: [{ min: 20, max: 20, message: '设备号长度为20' }],
        floor: [
          {
            validator: function(rule, value, callback) {
              if (value == null || value == '') {
                callback()
              }
              if (!Number.isInteger(value)) {
                callback(new Error('请输入正整数数字'))
              } else if (value < 0) {
                callback(new Error('请输入正整数数字'))
              } else {
                callback()
              }
            }
          }
        ],
        userMax: [
          {
            validator: function(rule, value, callback) {
              if (value == null || value == '') {
                callback()
              }
              if (!Number.isInteger(value)) {
                callback(new Error('请输入正整数数字'))
              } else if (value < 0) {
                callback(new Error('请输入正整数数字'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      checkICOption: {
        index: true,
        border: true,
        stripe: true,
        height: 300,
        editBtn: false,
        indexLabel: '序号',
        formWidth: '30%',
        menuAlign: 'center',
        delBtn: false,
        // menuWidth: 350,
        column: [
          {
            label: '电表名称',
            sortable: true,
            size: 'small',
            span: 24,
            prop: 'powerName',
            formsolt: true,
            rules: [
              {
                required: true,
                message: '请输入电表名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '电表ID',
            sortable: true,
            size: 'small',
            span: 24,
            addVisdiplay: false,
            editVisdiplay: false,
            prop: 'powerId'
          }
        ]
      },
      imgLimit: 1,
      imgPaths: [],
      imgList: [],
      imgListShow: [],
      imgFormVisible: false,
      uploadParams: { type: 'initialqr' },
      uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      },
      communityId: '',
      buildingId: '',
      unitId: '',
      guardQrForm: {},
      guardQrLoading: false,
      guardPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      guardQrOption: {
        index: true,
        border: true,
        stripe: true,
        height: 300,
        indexLabel: '序号',
        formWidth: '30%',
        menuAlign: 'center',
        dicData: DIC,
        column: [
          {
            label: '类型',
            size: 'small',
            prop: 'type',
            type: 'select',
            disabled: true,
            dicData: 'userType',
            rules: [
              {
                required: true,
                message: '请输入类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '图片',
            size: 'small',
            prop: 'imgPath',
            align: 'center',
            solt: true,
            span: 24,
            formsolt: true,
            disabled: true
          }
        ]
      },
      guardQrData: [],
      addQrInfoFormVisible: false, // 初始二维码管理界面是否显示
      listLoading: false,
      listQuery: {},
      dialogFormVisible: false,
      dialogStatus: '',
      pName: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      option: {
        columns: [
          {
            text: '设备名称',
            value: 'name',
            width: 300,
            align: 'center'
          },
          {
            text: '设备号',
            value: 'deviceId',
            width: 200,
            align: 'center'
          },
          {
            text: '设备编号',
            value: 'sort',
            align: 'center'
          },
          {
            text: '类型',
            value: 'type',
            type: 'dic',
            align: 'center',
            dicData: DIC.typeOptions
          },
          {
            text: '当前用户',
            value: 'userNow',
            align: 'center'
          },
          {
            text: '用户上限',
            value: 'userMax',
            align: 'center'
          }
        ],
        data: []
      },
      form: {}
    }
  },
  created() {
    this.listTree()
  },
  computed: {
    typeWatch() {
      if (this.form.type === '1') {
        if (this.dialogStatus == 'create') {
          this.form.deviceType = this.row.deviceType
        } else {
          if (this.row.parent != undefined) {
            this.form.deviceType = this.row.parent.deviceType
          } else {
            this.form.deviceType = this.row.deviceType
          }
        }
        return true
      }
      return false
    }
  },
  methods: {
    message(row) {
      const obj = Object.assign({}, row)
    },
    listTree() {
      this.listLoading = true
      fetchDeviceTree().then(response => {
        this.option.data = response.data.data.tree
        this.listLoading = false
      })
    },
    handleCreateCom() {
      this.pName = ''
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.form.guardPid = 0
    },
    handleCreate(row) {
      this.row = row
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.pName = row.name
      this.form.guardPid = row.id
      this.form.communityId = row.communityId
    },
    handleUpdate(row) {
      this.row = row
      this.resetForm()
      this.dialogStatus = 'update'
      this.form = Object.assign({}, row, {
        id: row.did,
        deviceName: row.name
      })
      this.pName = row.parent == null ? row.name : row.parent.name
      this.dialogFormVisible = true
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          add(this.form).then(data => {
            if (data.data.data) {
              this.dialogFormVisible = false
              this.listTree()
              this.$notify({
                title: '成功',
                message: data.data.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.data.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      const set = this.$refs
      set[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          let form = Object.assign({}, this.form)
          delete form.children
          delete form.parent
          put(form).then(data => {
            if (data.data.data) {
              this.dialogFormVisible = false
              this.listTree()
              this.$notify({
                title: '成功',
                message: data.data.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.data.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          return false
        }
      })
    },
    del(row) {
      this.$confirm(
        '此操作将删除该设备(设备名称:' + row.name + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        del(row.did)
          .then(() => {
            this.listTree()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .catch(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    resetForm() {
      this.form = {}
    },
    closeForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleQr(row) {
      if (row.deviceType === 'community') {
        this.communityId = row.communityId
        this.buildingId = ''
        this.unitId = ''
      } else if (row.deviceType === 'building') {
        this.communityId = row.communityId
        this.buildingId = row.id
        this.unitId = ''
      } else if (row.deviceType === 'unit') {
        this.communityId = row.communityId
        this.buildingId = row.parentId
        this.unitId = row.id
      }
      this.getList()
      this.addQrInfoFormVisible = true
    },
    getList(form) {
      this.guardQrLoading = true
      fetchList({
        page: this.guardPage.currentPage,
        limit: this.guardPage.pageSize,
        communityId: this.communityId,
        buildingId: this.buildingId,
        unitId: this.unitId
      }).then(response => {
        this.guardQrLoading = false
        this.guardQrData = response.data.records
        this.guardPage.total = response.data.total
      })
    },
    currentQrChange(val) {
      this.guardPage.page = val
      this.getList()
    },
    refreshQrChange(val) {
      this.getList()
      this.$message({
        showClose: true,
        message: '刷新成功',
        type: 'success'
      })
    },
    rowQrDel(row, index) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delObj(row.id)
        })
        .then(data => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        })
        .catch(function(err) {})
    },
    rowQrSave(row, done) {
      row.imgPath = this.imgPaths.toString()
      if (validatenull(row.imgPath)) {
        this.$message.warning(`请上传图片`)
      } else {
        addObj(
          Object.assign({}, row, {
            communityId: this.communityId,
            buildingId: this.buildingId,
            unitId: this.unitId
          })
        ).then(data => {
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          this.getList()
          done()
        })
      }
    },
    rowQrUpdate(row, index, done) {
      row.imgPath = this.imgPaths.toString()
      if (validatenull(row.imgPath)) {
        this.$message.warning(`请上传图片`)
      } else {
        putObj(row).then(data => {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          this.getList()
          done()
        })
      }
    },
    //图片点击事件
    imgHandlePreview: function(file) {},
    //图片删除事件
    imgHandleRemove: function(file, fileList) {
      this.imgPaths = []
      this.imgList = []
    },
    //图片上传之前验证格式
    beforeImgUpload: function(file) {
      const type = file.type
      const flag = [
        'image/jpeg',
        'image/gif',
        'image/png',
        'image/bmp'
      ].includes(type)
      if (!flag) {
        this.$message.error('只支持上传图片!')
      }
      return flag
    },
    //图片上传成功后
    imgSuccess: function(response, file, fileList) {
      var path = response.attributes.filepath
      this.imgPaths.push(path)
    },
    showImgPath(row) {
      this.imgListShow = []
      getImg(row.imgPath).then(res => {
        this.imgFormVisible = true
        this.imgListShow.push('data:image/gif;base64,' + res.data)
      })
    },
    imgExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除？`)
    },
    beforeQrClose(done) {
      this.imgPaths = []
      this.imgList = []
      done()
    },
    beforeQrOpen(show) {
      setTimeout(() => {
        if (!validatenull(this.guardQrForm.imgPath)) {
          this.imgList = []
          this.imgPaths = this.guardQrForm.imgPath
          getImg(this.guardQrForm.imgPath).then(res => {
            var name = this.guardQrForm.imgPath.split('/')
            this.imgList.push({
              name: name[1],
              url: `data:image/gif;base64,${res.data}`
            })
          })
        } else {
          this.imgList = []
        }
        show()
      }, 0)
    },
    rowDel(row, index) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delPowerObj(row)
        })
        .then(data => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getCheckPowerList()
        })
        .catch(function(err) {})
    },
    rowSave(row, done) {
      addPowerObj(Object.assign({}, row)).then(data => {
        this.$message({
          showClose: true,
          message: data.data.msg,
          type: 'success'
        })
        this.getCheckPowerList()
        this.rfidreader.Repeat = 0
        done()
      })
    },
    checkPower: function(index, row) {
      this.id = row.deviceId
      this.getCheckPowerList()
      this.checkPowerFormVisible = true
    },
    getCheckPowerList() {
      this.guardCheckPowerLoading = true
      getPowerById(this.id).then(response => {
        this.guardCheckPowerLoading = false
        this.checkPowerData = response.data.data
      })
    },
    refreshCheckPowerChange(val) {
      this.getCheckPowerList()
      this.$message({
        showClose: true,
        message: '刷新成功',
        type: 'success'
      })
    },
    currentCheckPowerChange(val) {
      this.guardPage.page = val
      this.getCheckPowerList()
    },
    syncIC(index, row) {
      this.listLoading = true
      syncByDeviceId(row.deviceId).then(response => {
        this.$message({
          showClose: true,
          message: '同步中',
          type: 'success'
        })
        this.listLoading = false
      })
    },
    deviceInit(index, row) {
      this.listLoading = true
      deviceInit(row.deviceId).then(response => {
        this.$message({
          showClose: true,
          message: '初始化成功',
          type: 'success'
        })
        this.listLoading = false
      })
    }
  }
}
</script>

<style lang="scss">
.image {
  width: 100%;
  display: block;
}
.avue-tree-table {
  .ms-tree-space {
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: 18px;
    height: 14px;
  }
}
</style>